﻿using System.Reflection;
using Zhp.Common.Appsetting;
using Zhp.IService.Base;
using Zhp.Service.Base;

namespace Zhp.Api.Extensions
{
    public static class ServiceCollectionSetup
    {
        /// <summary>
        /// 反射自动注入
        /// </summary>
        /// <param name="services"></param>
        /// <param name="implAssemblys"></param>
        /// <returns></returns>
        public static IServiceCollection AddServices(this IServiceCollection services) 
        {
            var program = AppSettingHelper.GetOptions<ProgramCodeOptions>();
            foreach (var assembly in program.ServiceNames) 
            {
                var serviceAssembly = Assembly.LoadFrom(Path.Combine(AppContext.BaseDirectory, $"{assembly}.dll"));
                var types = serviceAssembly.GetTypes().Where(x => x.IsVisible && ((TypeInfo)x).ImplementedInterfaces.Count() > 0);
                foreach (var impl in types)
                {
                    var interfaces = ((TypeInfo)impl).ImplementedInterfaces;
                    foreach (var inter in interfaces)
                    {
                        var exist = services.Any(x => x.ServiceType == inter);
                        if (!exist)
                        {
                            if (!inter.IsGenericType)
                            {
                                services.AddTransient(inter, impl);
                            }
                        }
                    }
                    
                }
            }

            services.AddTransient(typeof(IBaseService<>), typeof(BaseService<>));

            return services;
        }
    }
}
